package com.duleme.servlet;

import com.duleme.common.JsonUtils;
import com.duleme.dao.UserInfoDao;
import com.duleme.entity.User;
import com.duleme.entity.UserInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/update/userInfo")
public class UserInfoUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserInfo userInfo = (UserInfo) req.getSession().getAttribute("userInfo");
        UserInfoDao dao = new UserInfoDao();
        String birthday = req.getParameter("birthday");
        System.out.println(birthday);
        if (birthday != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            try {
                Date date = sdf.parse(birthday);
                userInfo.setBirthday(date);
            } catch (Exception e) {
                e.printStackTrace();
                resp.getWriter().print(JsonUtils.result2Json("0"));
            }

        }

        String sex = req.getParameter("sex");
        if (sex != null) userInfo.setSex(Integer.parseInt(sex));
        String phoneNumber = req.getParameter("phone");
        if (phoneNumber != null) userInfo.setPhoneNumber(phoneNumber);
        String emailAddress = req.getParameter("email");
        if (emailAddress != null) userInfo.setEmailAddress(emailAddress);
        boolean result = dao.updateUserInfo(userInfo);
        System.out.println(userInfo.getUserId());
        System.out.println(userInfo.getEmailAddress());
        System.out.println(userInfo.getBirthday());
        System.out.println(userInfo.getPhoneNumber());
        System.out.println(userInfo.getSex());
        if(result){
            req.getSession().setAttribute("userInfo",userInfo);
            String json=JsonUtils.result2Json("1");
            System.out.println();
            resp.getWriter().print(JsonUtils.result2Json("1"));
        }else {
            resp.getWriter().print(JsonUtils.result2Json("0"));

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
